// ActionScript file
import com.nstar.base.event.RequestEvent;
import com.nstar.base.util.EffectUtils;
import com.nstar.base.util.GraphicsUtils;
import com.nstar.jianli.components.AdviceEditor;
import com.nstar.jianli.components.GraphicSelector;
import com.nstar.jianli.components.JianLiEditor;
import com.nstar.jianli.components.JianLiPreviewer;
import com.nstar.jianli.components.SkillEditor;
import com.nstar.jianli.components.SkillTag;
import com.nstar.jianli.components.TextEditor;
import com.nstar.jianli.components.Toast;
import com.nstar.jianli.components.WorkTag;
import com.nstar.jianli.components.YearButton;
import com.nstar.jianli.controller.WeiboController;
import com.nstar.jianli.view.Constant;
import com.nstar.jianli.vo.JianLiVO;
import com.nstar.jianli.vo.SkillVO;
import com.nstar.jianli.vo.UserVO;
import com.sina.microblog.data.MicroBlogStatus;
import com.sina.microblog.events.MicroBlogEvent;

import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.geom.Point;
import flash.system.Capabilities;
import flash.utils.Timer;

import mx.graphics.ImageSnapshot;
import mx.graphics.codec.PNGEncoder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;


private const pngEnc:PNGEncoder = new PNGEncoder();
public static const RESUME_LIST:String = "resumeList"; 


public var _controller:WeiboController;

private var timer:Timer = new Timer(30*1000);//30秒钟查一次数据

private var workStyleType:String = WorkTag.TYPE_RECT;
private var skillStyleType:String = SkillTag.TYPE_COLUMN;

private function init():void{
	
	var filters:Array = EffectUtils.shadowFilter();
	//txtSample.filters = txtLogin.filters = txtPlaza.filters = txtHelp.filters = txtAdvice.filters = filters;
	txtTitle1.filters = txtTitle2.filters = filters;
	txtDesc1.filters = txtDesc2.filters = filters;
	
	timer.addEventListener(TimerEvent.TIMER,timerHandler);
	
//	GraphicsUtils.drawBackground(imgGrayLine,userArea);
	
	//先查询一次
	pollQuery.send();
	//更新访问次数
	upadteCount(Constant.ACCESS_COUNT);
	
	this.invalidateDisplayList();
}

public function get controller():WeiboController{
	return this._controller;
}

public function set controller(value:WeiboController):void{
	this._controller = value;
}

private function timerHandler(event:TimerEvent):void{
	pollQuery.send();
}


//用户验证成功后刷新
public function refresh():void{
	txtAdvice.visible = txtAdvice.includeInLayout =true;
	imgUser.source = controller.user.profileImageUrl;
	txtName.text = controller.user.screenName;
	txtJobs.text = controller.user.description;
	txtChange.text = "换个用户？";
	//更新登录次数
	upadteCount(Constant.LOGIN_COUNT);
}

//复位数据
public function reset():void{
	controller.logined = false;
	txtName.text = "";
	txtJobs.text = "";
	imgUser.source = null;
	
	//重新登录
	loginHandler();
}

private function loginHandler():void{
	_controller.getMicroBlog().login();
}


private function addJianLiHandler(event:MouseEvent):void{
	 var editor:JianLiEditor = JianLiEditor.show();
	editor.addEventListener(JianLiEditor.CREATED_JIANLI,addCompleteHandler);
	editor.addEventListener(JianLiEditor.CLOSE,closeJianLiEditorHandler);  
	 
	var p:Point = event.target.localToGlobal(new Point());
	var w2:Number = 620;
	var h2:Number = 310;
	var x2:Number = (this.width-w2)/2;
	var y2:Number = (this.height-h2)/2;
	EffectUtils.removeTween();
	EffectUtils.playTween(editor,{x:p.x,y:p.y,width:event.target.width,height:event.target.height,alpha:0.8},
		{x:x2,y:y2,width:w2,height:h2,alpha:1,time:1});
	 	
}

private function closeJianLiEditorHandler(event:Event):void{
//	event.target.hide();
	 
	var p:Point = btnAdd1.localToGlobal(new Point());
	var target:Object = event.target;
	EffectUtils.playTween(target,{x:target.x,y:target.y,width:target.width,height:target.height,alpha:1},
		{x:p.x,y:p.y,width:btnAdd1.width,height:btnAdd1.height,alpha:0,time:0.5,onComplete:function(){target.hide();}});
	 	
}


private function addCompleteHandler(event:RequestEvent):void{
	var vo:JianLiVO = event.request as JianLiVO;
	//处理年份
	var years:Array = [vo.startYear,vo.endYear];
	experienceList.addYears(years);
	
	//处理简历
	trace("event.type="+event.type);
	switch(event.type){
		case JianLiEditor.CREATED_JIANLI:
			var tag:WorkTag = new WorkTag();
			//tag.addEventListener(WorkTag.EDIT,editJianLiHandler);
			tag.jianliVO = vo;
			tag.setStyle("bottom",experienceList.height-5);
			experiences.addChildAt(tag,0);
//			btnAdd1.visible = btnAdd1.includeInLayout = false;
//			txtDesc1.visible = txtDesc1.includeInLayout = false;
			break;
		case JianLiEditor.UPDATE_JIANLI:
			updateWorkTag(vo);
			break;
	}
	
	relayoutExperiences();
}

private function editJianLiHandler(event:RequestEvent):void{
	var editor:JianLiEditor = JianLiEditor.show(event.request as JianLiVO);
	editor.addEventListener(JianLiEditor.UPDATE_JIANLI,addCompleteHandler);
	editor.addEventListener(JianLiEditor.CLOSE,closeJianLiEditorHandler);
}

private function updateWorkTag(vo:JianLiVO):void{
	for each(var item:Object in experiences.getChildren()){
		if(item is WorkTag){
			if(WorkTag(item).jianliVO.id == vo.id){
				WorkTag(item).jianliVO = vo;
				break;
			}
		}
	}
}

//重新设置工作经历的位置
private function relayoutExperiences():void{
	for each(var item:Object in experiences.getChildren()){
		if(item is WorkTag){
			var tag:WorkTag = WorkTag(item);
			var yearButton:YearButton = experienceList.getYearButton(tag.jianliVO.startYear);
			tag.updateTagWidth(experienceList.monthWidth);
			tag.updateTagPosition(yearButton,experienceList.monthWidth);
			tag.validateNow();
			tag.drawBackground(workStyleType);//workStyleType
//			tag.playTween(experienceList.monthWidth,yearButton,experienceList.monthWidth);
		}
	}
}

private function addSkillsHandler(event:MouseEvent):void{
	var editor:SkillEditor = SkillEditor.show();
	editor.addEventListener(SkillEditor.CREATED_SKILLS,addSkillsCompleteHandler);
	editor.addEventListener(SkillEditor.CLOSE,closeSkillEditorHandler); 
	 
	var p:Point = event.target.localToGlobal(new Point());
	var w2:Number = 460;
	var h2:Number = 240;
	var x2:Number = (this.width-w2)/2;
	var y2:Number = (this.height-h2)/2;
	EffectUtils.removeTween();
	EffectUtils.playTween(editor,{x:p.x,y:p.y,width:event.target.width,height:event.target.height,alpha:0.8},
		{x:x2,y:y2,width:w2,height:h2,alpha:1,time:1});
	 
}

private function closeSkillEditorHandler(event:Event):void{
//	event.target.hide();
	 var p:Point = btnAdd2.localToGlobal(new Point());
	var target:Object = event.target;
	EffectUtils.playTween(target,{x:target.x,y:target.y,width:target.width,height:target.height,alpha:1},
		{x:p.x,y:p.y,width:btnAdd2.width,height:btnAdd2.height,alpha:0,time:0.5,onComplete:function(){target.hide();}});
	 	
}


private function addSkillsCompleteHandler(event:RequestEvent):void{
	var vo:SkillVO = event.request as SkillVO;
	switch(event.type){
		case SkillEditor.CREATED_SKILLS:
			var skillTag:SkillTag = new SkillTag();
			skillTag.addEventListener(SkillTag.EDIT,editSkillHandler);
			skillTag.skillVO = vo;
			skillTag.setStyle("bottom",0);
			skills.addChildAt(skillTag,0);		
			break;
		case SkillEditor.UPDATE_SKILLS:
			updateSkillTag(vo);
			break;
	}

	
	relayoutSkills();
}

private function editSkillHandler(event:RequestEvent):void{
	var editor:SkillEditor = SkillEditor.show(event.request as SkillVO);
	editor.addEventListener(SkillEditor.UPDATE_SKILLS,addSkillsCompleteHandler);
	editor.addEventListener(SkillEditor.CLOSE,closeSkillEditorHandler);
}

private function updateSkillTag(vo:SkillVO):void{
	for each(var item:Object in skills.getChildren()){
		if(item is SkillTag){
			if(SkillTag(item).skillVO.id == vo.id){
				SkillTag(item).skillVO = vo;
				break;
			}
		}
	}
}


//重排技能图表
private function relayoutSkills():void{
	var count:int = skills.numChildren - 4;
	var w:Number = skills.width/(count+1);
	var idx:int = 1;
	for each(var item:Object in skills.getChildren()){
		if(item is SkillTag){
			var tag:SkillTag = SkillTag(item);
			tag.x = idx*w;
			tag.drawBackground(skillStyleType);
			idx++;
		}
	}
}

private static const NA:String = "N/A";
private function previewHandler():void{
	if(controller.debugMode==true || controller.logined){
		if(this.worksCount==0){
			Toast.show("还没有添加任何履历哦~");
			return;
		}
		
		if(this.skillsCount==0){
			Toast.show("还没有添加任何技能呢~");
			return;
		}
		
		if(txtTele.text == NA){
			Toast.show("不设置电话了么，怎么联系你呢？");
			return;
		}
		
		var user:UserVO = new UserVO();
		user.name = txtName.text;
		user.jobs = txtJobs.text;
		initCapture(false);
		var imageSnap:ImageSnapshot = ImageSnapshot.captureImage(jianli, 0, pngEnc); 
		var viewer:JianLiPreviewer =  JianLiPreviewer.show(txtJobs.text,user,imageSnap.data as ByteArray,_controller.getMicroBlog());
		viewer.addEventListener(MicroBlogEvent.UPDATE_STATUS_RESULT,updateStatusHandler);
		initCapture(true);
	}else{
		Toast.show("请先使用新浪微博帐号登录");
	}

}

private function initCapture(visible:Boolean):void{
	btnExpStyle.visible = btnExpStyle.includeInLayout = visible;
	btnSkillStyle.visible = btnSkillStyle.includeInLayout = visible;
}

//保存发布的简历信息
private function updateStatusHandler(event:MicroBlogEvent):void{
	var status:MicroBlogStatus = event.result as MicroBlogStatus;
	insetStatusHandler(status);
}

override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void{
	super.updateDisplayList(unscaledWidth,unscaledHeight);
	if(this.initialized){
		this.validateNow();
		
		GraphicsUtils.drawZebraStripe(experiences,0xFFFFFF,0xFBFBFB,20);
		GraphicsUtils.drawZebraStripe(skills,0xFBFBFB,0xFFFFFF,20,"h");
		this.graphics.beginFill(0x00C4F9);
		this.graphics.drawRect(-10,0,this.width+10,22);
	}
}

private function whatisthis():void{
	
}

private function sample():void{
	var u:URLRequest = new URLRequest("sample.jpg");
	navigateToURL(u,"_blank");
}

private function gotoResumeListHandler():void{
	this.dispatchEvent(new Event(RESUME_LIST));	
}

private function adviceHandler():void{
	if(controller.debugMode==true || controller.logined){
		var advicer:AdviceEditor = AdviceEditor.show();
		advicer.addEventListener(AdviceEditor.ADVICE,startAdviceHandler);
	}else{
		Toast.show("请先登录哦~");
	}
}

private function startAdviceHandler(event:RequestEvent):void{
	controller.advice("#我给时间轴提意见# "+event.request as String);
}

//新建微博简历，清空已有数据
private function newHandler():void{
	for each(var item:DisplayObject in experiences.getChildren()){
		if(item is WorkTag){
			experiences.removeChild(item);
		}
	}
	
	for each(var item:DisplayObject in skills.getChildren()){
		if(item is SkillTag){
			skills.removeChild(item);
		}
	}	
	
	experienceList.reset();
}


//更新计数器
private function upadteCount(type:int):void{
	var request:Object = new Object();
	request.type = type;
	updateCount.send(request);
}

private function updateCountResultHandler(event:ResultEvent):void{
	trace("update count ok");
}


private function pollQueryResultHandler(event:ResultEvent):void{
	var countStr:String = event.result+"";
	var counts:Array = countStr.split(";");
}

//保存用户发布的微博信息
private function insetStatusHandler(status:MicroBlogStatus):void{
	var statusUrl:String = "http://api.t.sina.com.cn/" + status.user.id + "/statuses/" + String(status.id);
	var request:Object = new Object();
	request.id = status.id;
	request.user_id = status.user.id;
	request.name = status.user.screenName;
	request.profile_image_url = status.user.profileImageUrl;
	request.status_url = statusUrl;
	insertStatus.send(request);
}

private function insertStatusResultHandler(event:ResultEvent):void{
	trace("insert resume status ok");
}

//插入用户数据
//private function insertHandler(statusUrl:String):void{
//	var request:Object = new Object();
//	request.id = controller.user.id;
//	request.name = controller.user.screenName;
//	request.profile_image_url = controller.user.profileImageUrl;
//	request.status_url = statusUrl;
//	request.remarks= "";
//	insertStatus.send(request);
//}


private function faultHandler(event:FaultEvent):void
{
	Toast.show("error");
}

private function  expStyleSelectHandler():void{
	var p:Point = btnExpStyle.localToGlobal(new Point());
	var x1:Number = p.x+btnExpStyle.width-GraphicSelector.WIDTH;
	var y1:Number = p.y+btnExpStyle.height -6;
	
	var ymax:Number = Capabilities.screenResolutionY;
	var style:String = "selectorBgUp";
	
	if(y1+GraphicSelector.HEIGHT>ymax){
		y1 = y1- GraphicSelector.HEIGHT - btnExpStyle.height;
		style = "selectorBgDown";
	}
	var selector:GraphicSelector = GraphicSelector.show("assets/experience_style.xml",x1,y1,style);
	selector.addEventListener(GraphicSelector.SELECTED,selectExpStyleHandler);
	
}

private function  skillStyleSelectHandler():void{
	var p:Point = btnSkillStyle.localToGlobal(new Point());
	var x1:Number = p.x+btnExpStyle.width-GraphicSelector.WIDTH;
	var y1:Number = p.y+btnExpStyle.height;	
	var style:String = "selectorBgUp";
	if(y1+GraphicSelector.HEIGHT>this.height){
		y1 = y1- GraphicSelector.HEIGHT - btnExpStyle.height+4;
		style = "selectorBgDown";
	}	
	var selector:GraphicSelector = GraphicSelector.show("assets/skill_style.xml",x1,y1,style);
	selector.addEventListener(GraphicSelector.SELECTED,selectSkillStyleHandler);
	
}

private function selectExpStyleHandler(event:RequestEvent):void{
	var item:Object = event.request;
	workStyleType = item.type;
	relayoutExperiences();
}

private function selectSkillStyleHandler(event:RequestEvent):void{
	var item:Object = event.request;
	skillStyleType = item.type;
	relayoutSkills();
}

//更换用户
private function changeUserHandler(event:MouseEvent):void{
	if(controller.logined){
		controller.getMicroBlog().logout();
	}else{
		controller.getMicroBlog().login();
	}
	
}

//获得履历添加的数量
public function get worksCount():int{
	var result:int = 0;
	for each(var item:Object in experiences.getChildren()){
		if(item is WorkTag){
			result++;
		}
	}
	return result;
}
//添加的技能数量
public function get skillsCount():int{
	var result:int = 0;
	for each(var item:Object in skills.getChildren()){
		if(item is SkillTag){
			result++;
		}
	}
	return result;
}


private function expRollHandler(event:MouseEvent):void{
	switch(event.type){
		case MouseEvent.ROLL_OVER:
			btnAdd1.visible = btnAdd1.includeInLayout = true;
			txtDesc1.visible = txtDesc1.includeInLayout = true;
			break;
		case MouseEvent.ROLL_OUT:
			btnAdd1.visible = btnAdd1.includeInLayout = false;
			txtDesc1.visible = txtDesc1.includeInLayout = false;
			break;
	} 
}

private function skillsRollHandler(event:MouseEvent):void{
	switch(event.type){
		case MouseEvent.ROLL_OVER:
			btnAdd2.visible = btnAdd2.includeInLayout = true;
			txtDesc2.visible = txtDesc2.includeInLayout = true;
			break;
		case MouseEvent.ROLL_OUT:
			btnAdd2.visible = btnAdd2.includeInLayout = false;
			txtDesc2.visible = txtDesc2.includeInLayout = false;
			break;
	} 
}

var editorRelaButton:Object;
private function editHandler(event:MouseEvent):void{
	var text:String = "";
	switch(event.currentTarget){
		case btnEdit1:	
		case txtName:
			text = txtName.text;break;
		case btnEdit2:	
		case txtJobs:
			text = txtJobs.text;break;
		case btnEdit3:	
		case txtTele:
			text = txtTele.text;break;
		case btnEdit4:
		case txtEmail:	
			text = txtEmail.text;break;
	}
	var editor:TextEditor = TextEditor.show(text);
	editor.addEventListener(TextEditor.OK,textHandler);
	editorRelaButton = event.currentTarget;
	
	var p:Point = event.currentTarget.localToGlobal(new Point());
	var x1:Number = p.x+event.currentTarget.width - editor.width;
	var y1:Number = p.y;
	
	if(x1<0) x1 = 2;
	if(x1+editor.width>this.width) x1 = this.width - editor.width - 5; 
	
	editor.x = x1;
	editor.y = y1+50;
	editor.alpha = 0;
	EffectUtils.playTween(editor,null,{x:x1,y:y1,time:1,alpha:1});
}


private function textHandler(event:RequestEvent):void{
	var text:String = event.request as String;
	trace("text>>"+text);
	switch(editorRelaButton){
		case btnEdit1:	
		case txtName:
			txtName.text = text;
			break;
		case btnEdit2:	
		case txtJobs:
			txtJobs.text = text;
			break;
		case btnEdit3:	
		case txtTele:
			txtTele.text = text;
			break;
		case btnEdit4:
		case txtEmail:	
			txtEmail.text = text;
			break;
	}
}

